const Router = require('koa-router')
const pug = require('pug');
const fs = require('fs')
const path = require('path')
let router = new Router()

const getProject = function (){
  return new Promise(function (resolve, reject){
    fs.readdir(path.resolve(__dirname,'../project'), ( err, folders)=>{
      if (err) reject(err);
      resolve(folders);
    });
  });
};

router.all('/:project', async ctx => {
        const folder = ctx.originalUrl.substring(1).split("?")[0]
        console.log(ctx.originalUrl.substring(1).split("?")[0])
        ctx.response.type = 'html';
        ctx.response.body = fs.createReadStream(`${folder}/index.html`);
        // ctx.response.body = ctx;
  })
router.all('*', async ctx => {
        // const folder = ctx.originalUrl.substring(1).split("?")[0]
        // console.log(ctx.originalUrl.substring(1).split("?")[0])
        let Project = await getProject()
        // pug.renderFile('index.pug', {
        //     Project
        // })
        ctx.response.type = 'html';
        // ctx.response.body = fs.createReadStream(`/`);
        ctx.response.body = pug.renderFile('index.pug', {
            Project
        });
  })

module.exports = router